<?php
namespace app\controller;

use app\BaseController;
use app\controller\model\Config;
use app\controller\model\Pay;
use app\controller\model\Tables;
use liliuwei\think\Auth;
use think\facade\Session;
use think\facade\Db;
class Crontab extends BaseController
{
    //计划任务，每分钟执行一次
    // php /public/index.php Crontab/index zaoufoas
    protected $dingModel;
    protected $m=0;//分钟执行
    protected $nowTimeD;
    protected $nowTimeH;
    protected $nowTimeM;
    protected $tables;
    public function __construct(){
        //设置只允许本地执行
	    //*/1 * * * * php /www/jiuzhouxing/public/index.php Crontab/index zaoufoas  >> /www/log/jiuzhouxing/crontablog/$(date +"\%Y-\%m-\%d").txt
        $this->tables=new Tables();
        $ip = request()->ip();
	    try {
//			if(!isset($_SERVER['argv'])){
//				exit("需本地执行"."\n");
//			}
//		    $code = $_SERVER['argv'][2];
//		    if($ip!="0.0.0.0"){
//			    exit("需本地执行"."\n");
//		    }
//		    if($code!="zaoufoas"){
//			    exit("密码错误"."\n");
//		    }
	    }catch (\Exception $e){
			echojson([],1,'错误');
	    }
	    ini_set('max_execution_time', 90);
        echo nowTime()."执行开始：".microtime()."\n";
        //开始各种model加载
        $this->nowTimeD = date("d");
        $this->nowTimeH = date("H");
        $this->nowTimeM = date("i");
    }
    public function index(){
        //每分钟执行的
        $this->one();
        //每10分钟执行的
        if($this->nowTimeM % 10 == 0){

        }
        //每小时执行的
        if($this->nowTimeM == 59){

        }
        //每天凌晨3点需要执行的
        if($this->nowTimeH == "03" && $this->nowTimeM=="00"){

        }
        //每天10点需要执行的
        if($this->nowTimeH == "22" && $this->nowTimeM=="00"){

        }
	    //每天00点需要执行的 每分钟一次
	    if($this->nowTimeH == "00" && intval($this->nowTimeM) > 15){
		    $model = new \app\controller\model\Supplier(4);
		    $model->getGasList(1);
			sleep(10);
		    $model2 = new \app\controller\model\Supplier(2);
		    $model2->getGasList(1);
	    }
        //每天6点需要执行的 整个6点每分钟一次
        if($this->nowTimeH == "06" && intval($this->nowTimeM) > 15){
	        $model = new \app\controller\model\Supplier(4);
	        $model->getGasList(2);
	        sleep(10);
	        $model2 = new \app\controller\model\Supplier(2);
	        $model2->getGasList(2);
        }
        //每天12点需要执行的 每分钟一次
        if($this->nowTimeH == "12" && intval($this->nowTimeM) > 15){
	        $model = new \app\controller\model\Supplier(4);
	        $model->getGasList(3);
	        sleep(10);
	        $model2 = new \app\controller\model\Supplier(2);
	        $model2->getGasList(3);
        }
        //每天18点需要执行的 每分钟一次
        if($this->nowTimeH == "18" && intval($this->nowTimeM) > 15){
	        $model = new \app\controller\model\Supplier(4);
	        $model->getGasList(4);
	        sleep(10);
	        $model2 = new \app\controller\model\Supplier(2);
	        $model2->getGasList(4);
        }
        //每天凌晨22点30需要执行的
        if($this->nowTimeH == "22" && intval($this->nowTimeM) > 49){

        }
        //每个月一号需要执行的
        if($this->nowTimeD == "01" && $this->nowTimeH == "03" && $this->nowTimeM=="20"){

        }
        $this->runEnd();
    }
	public function test(){
		$this->taskService();
	}
    public function one(){
	    sleep(2);
	    $this->task();
	    sleep(2);
	    $this->taskService();
	    sleep(2);
	    $this->pushGas();
    }
	protected function pushGas(){
		//如果pushNumber < upNumber则向服务商推送数据
		$gas = DB::name($this->tables->gas)->field("id,gasID,tipsID,upNumber")->where("pushNumber < upNumber")->limit(0,50)->select();//保持和服务商获取列表接口一致50条，服务商可以不用处理获取列表数据
		if(!$gas)return false;
		$serviceModel = new Service(false);
		$services = DB::name($this->tables->service)->field("id,url,status,inGasTips")->where("status",0)->select();
		foreach ($services as $k => $v){
			$inGasTips = explode(",",$v['inGasTips']);
			$temGas=[];
			foreach ($gas as $v2){
				if($k==0){
					DB::name($this->tables->gas)->where("id",$v2['id'])->update(['pushNumber'=>$v2['upNumber']]);
				}
				if(is_array($inGasTips) && count($inGasTips)>0 && $inGasTips[0]!=''){
					if(in_array($v2['tipsID'],$inGasTips)){
						$temGas[] = $v2['gasID'];
					}
				}else{
					$temGas[] = $v2['gasID'];
				}
			}
			if(count($temGas)>0){
				echo  "发送到服务商".$v['id']."\r\n";
				$serviceModel->pushService($v['id'],'gas',implode(",",$temGas));
			}

		}
	}
	protected function taskService(){
		//执行计划任务  1让利比例，2固定金额降价,3选择油号
		$res = DB::name($this->tables->taskService)->where("status",0)->where("taskTime","<=",nowTime())->select();
		foreach ($res as $v){
			$db = DB::name($this->tables->service)->whereIn("tipsID",$v['tipsIDS']);
			if($v['ctype']==1){
				$tipsGasIDS = $v['tipsGasIDS'];
				$percent = $v['percent'];
				if(is_string($tipsGasIDS) && strlen($tipsGasIDS)>0){
					lock();
					//说明指定了油站标签
					//读取油站标签所有加油站  然后写入gas_service_price
					$service = explode(",",rTipsToServiceIDS($v['tipsIDS']));
					$gasIDS = explode(",",rTipsToIds2($tipsGasIDS));//得到所有标签对应的油站IDS   要准备开始写入到gas_service_price了
					$serviceModel = new Service(false);
					foreach ($gasIDS as $v2){
						if($v2<1)continue;
						foreach ($service as $v3){
							if($v3<1)continue;
							$re = $serviceModel->setGasServicePrice($v2,$v3,$percent);
							if(!$re)unlockRollback();
						}
					}
					unlockCommit();
				}else{
					//让利比例会清空固定金额降价 因为金额权重大于比例
					$db->update(['subPercent'=>$v['percent'],'subPrice'=>0]);
				}
			}
			if($v['ctype']==2){
				$db->update(['subPrice'=>$v['rule']]);
			}
			if($v['ctype']==3){
				$db->update(['inOilNo'=>$v['inOil']]);
			}
			DB::name($this->tables->taskService)->where("id",$v['id'])->update(['status'=>1]);
		}
	}
	protected function task(){
		//执行计划任务
		$res = DB::name($this->tables->taskGas)->where("status",0)->where("taskTime","<=",nowTime())->select();
		foreach ($res as $v){
			$gasIDS = rTipsToIds($v['tipsIDS']);
			if($v['ctype']==2){
				$priceNew = $this->taskRule(json_decode($v['rule'],true));
				//通过标签读取所有油站 包含禁用的
				//
				foreach ($priceNew as $v2){
					$oil_no = $v2[0];
					unset($v2[0]);
					$price['prices'] = $v2;
					DB::name($this->tables->gas)->alias("a")->whereIn("a.id",$gasIDS)->leftJoin($this->tables->gasPrice." b","b.gasID=a.id")->where("b.oil_no",$oil_no)->update(['b.tail'=>json_encode($price)]);
				}

			}
			if($v['ctype']==1){
				$percent = $v['percent'];
				DB::name($this->tables->gas)->alias("a")->whereIn("a.id",$gasIDS)->leftJoin($this->tables->gasPrice." b","b.gasID=a.id")->update(['b.tail'=>null,"a.subPrice"=>$percent]);
			}
			DB::name($this->tables->taskGas)->where("id",$v['id'])->update(['status'=>1]);
		}
	}
	protected function taskRule($rule=[]){
		//处理任务的油价rule 如果任意字段为零表示该号油不设置
		$oil_no=[];
		foreach ($rule as $k=>$v){
			if(!in_array(0,$v) && !in_array("0",$v) && !in_array(null,$v) && !in_array("",$v)){
				if ($k==0)$oil_no[]=array_merge(['92#'],$v);
				if ($k==1)$oil_no[]=array_merge(['95#'],$v);
				if ($k==2)$oil_no[]=array_merge(['98#'],$v);
				if ($k==3)$oil_no[]=array_merge(['0#'],$v);
			}
		}
		return $oil_no;
	}
    protected function runEnd(){
        echo "执行完毕：".microtime()."\n";
        exit();
    }
}
